package com.example.SearchAround_JC.jc_activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.example.SearchAround_JC.R;
import com.example.SearchAround_JC.jc_manager.Distance;
import com.example.SearchAround_JC.jc_manager.PoiDetails;
import com.example.SearchAround_JC.jc_manager.PoiResult;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jing on 2014/11/25.
 */
public class PoiListActivity extends FragmentActivity {

    List<String> rangeDiaList = new ArrayList<String>();
    List<HashMap<String, String>> hashMapList = new ArrayList<HashMap<String, String>>();

    private ListView diaListview;
    private RelativeLayout map_RelativeLayout;
    private ListView poi_list_ListView;
    private Button poiDropBt;
    private Button poi_list_back_bt;
    private MapView mapView;
    private BaiduMap baiduMap;
    private Marker marker;
    private int f = 0;
    PoiListSimapleAdapter adapter1;

    private TextView poiRangeTextView;
    private TextView poiTextView;
    int childCount = -1;
    private Button diaConfirmBt;

    private Button listBt;
    private Button mapBt;
    private Button poi_pre_bt;
    private Button poi_next_bt;
    private Button poi_loction_bt;
    String q;
    String coordinate;
    String range;
    int counts = 8;
    List<PoiDetails> poiList = new ArrayList<PoiDetails>();
    //覆盖物图
    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_normal);
    private InfoWindow mInfoWindow;
    //定位
    LocationClient myLocation;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    boolean isFirstLoc = true;// 是否首次定位
    public MyLocationListenner myListener = new MyLocationListenner();

    //对话框
    AlertDialog.Builder dialog;
    AlertDialog alertDialog;
    ProgressDialog progressDialog;

    //当前页显示
    int currentPage = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SDKInitializer.initialize(this.getApplication());
        setContentView(R.layout.poi_list_activity);

        SharedPreferences preferences = getSharedPreferences("editor_range",MODE_PRIVATE);
        range = preferences.getString("range","3000");
        SharedPreferences sharedPreferences = getSharedPreferences("coordinate", MODE_PRIVATE);
        coordinate = sharedPreferences.getString("coordinate", "");

        final Intent intent = getIntent();
        String poiName = intent.getStringExtra("thirdName");
        q = poiName;
        poiTextView = (TextView) findViewById(R.id.poi_TextView);
        poiTextView.setText(poiName);

        //初始化poiList数据
        getPoi(coordinate, q, range, counts);
        Log.d("fagggggggggggg",hashMapList.size()+"");
        poi_list_ListView = (ListView) findViewById(R.id.poi_list_ListView);
        //添加listView的"更多子项"
        View moreView = LayoutInflater.from(this).inflate(R.layout.morepoi,null);
        moreView.setMinimumHeight(80);
        poi_list_ListView.addFooterView(moreView);





        poiRangeTextView = (TextView) findViewById(R.id.poi_range_TextView);
        map_RelativeLayout = (RelativeLayout) findViewById(R.id.map_RelativeLayout);
        SharedPreferences poiRange_sharedPreferences1 = getSharedPreferences("editor_range",MODE_PRIVATE);

        poiRangeTextView.setText(poiRange_sharedPreferences1.getString("range","3000m内"));

        poi_list_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == hashMapList.size()) {
                    counts += 6;
                    getPoi(coordinate, q, range, counts);
                    Log.d("nextDatas", "更多数据");
                } else {
                    HashMap<String,String> itemHashMap =
                            (HashMap<String, String>) parent.getItemAtPosition(position);
//                    itemHashMap.get("");
                    Intent intent1 = new Intent(PoiListActivity.this, POIdetails_Activity.class);
                    intent1.putExtra("name", itemHashMap.get("name"));
                    intent1.putExtra("distance", itemHashMap.get("distance"));
                    intent1.putExtra("tel", itemHashMap.get("tel"));
                    intent1.putExtra("address", itemHashMap.get("address"));
                    intent1.putExtra("y", itemHashMap.get("y"));
                    intent1.putExtra("x", itemHashMap.get("x"));
                    startActivity(intent1);
                }
            }
        });
        //结束这个界面

        poi_list_back_bt = (Button) findViewById(R.id.poi_list_back_bt);
        poi_list_back_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        //初始化对话框数据
        InitData();
        dialog = new AlertDialog.Builder(PoiListActivity.this);
        final View view = LayoutInflater.from(PoiListActivity.this).inflate(R.layout.poi_choose_dialog, null);
        diaListview = (ListView) view.findViewById(R.id.poi_alertdialog_listview);
        dialogAdapter adapter = new dialogAdapter(this, R.layout.poi_alertdialog_item, rangeDiaList);
        diaListview.setAdapter(adapter);
        alertDialog = dialog.create();
        alertDialog.setView(view);

        diaConfirmBt = (Button) view.findViewById(R.id.diaConfirm_bt);
        diaConfirmBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        poi_list_back_bt = (Button) findViewById(R.id.poi_list_back_bt);
        poiDropBt = (Button) findViewById(R.id.poi_drop_bt);
        poiDropBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.show();
            }
        });
        mapBt = (Button) findViewById(R.id.poi_map_bt);

        poi_pre_bt = (Button) findViewById(R.id.poi_pre_bt);
        poi_pre_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("OnClickListener","点击了上一个POi");

            }
        });
        poi_next_bt = (Button) findViewById(R.id.poi_next_bt);
        poi_next_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("OnClickListener","点击了下一个POi");
            }
        });
        poi_loction_bt = (Button) findViewById(R.id.poi_loction_bt);
        poi_loction_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("OnClickListener","点击了loction");
                mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                baiduMap
                        .setMyLocationConfigeration(new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker));
            }
        });


        mapView = (MapView) findViewById(R.id.baidu_MapView);
        baiduMap = mapView.getMap();
        //设置缩放级别
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(16).build()));
        //列表和地图的切换
        listBt = (Button) findViewById(R.id.poi_list_bt);
        listBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                map_RelativeLayout.setVisibility(View.GONE);
                poi_list_ListView.setVisibility(View.VISIBLE);
                listBt.setVisibility(View.GONE);
                mapBt.setVisibility(View.VISIBLE);
            }
        });
        mapBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                map_RelativeLayout.setVisibility(View.VISIBLE);
                mapView.showZoomControls(false);

                poi_list_ListView.setVisibility(View.GONE);
                mapBt.setVisibility(View.GONE);
                listBt.setVisibility(View.VISIBLE);
                for (int i = 0; i < poiList.size(); i++) {
                    PoiDetails poiDetails = poiList.get(i);
                    double x = Double.parseDouble(poiDetails.getX());
                    double y = Double.parseDouble(poiDetails.getY());
                    String name = poiDetails.getName();
                    overlay(y, x,name);
                }
            }
        });
        //Marker的点击事件
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

//                PoiDetails poiDetails = poiList.get(1);
                TextView textView = new TextView(getApplicationContext());
                textView.setBackgroundResource(R.drawable.bg_pop);
                textView.setTextColor(Color.BLACK);
                textView.setText(marker.getTitle());
                LatLng ll = marker.getPosition();
                mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(textView), ll, -47, null);
                baiduMap.showInfoWindow(mInfoWindow);
                Log.d("Marker","点击");
                return false;
            }
        });

        

        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        baiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, mCurrentMarker));
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 定位初始化
        myLocation = new LocationClient(this);
        myLocation.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("gcj02"); // 设置坐标类型
        myLocation.setLocOption(option);
        myLocation.start();
    }

    class dialogAdapter extends ArrayAdapter<String> {
        int resourceId;

        public dialogAdapter(Context context, int resource, List<String> objects) {
            super(context, resource, objects);
            resourceId = resource;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final String ranges = getItem(position);
            View view = LayoutInflater.from(PoiListActivity.this).inflate(resourceId, null);
            TextView textView = (TextView) view.findViewById(R.id.poi_dia_textView);
            textView.setText(ranges);
            RadioButton radioButton = (RadioButton) view.findViewById(R.id.poi_dia_radioBt);
            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    for (int i = 0; i < diaListview.getChildCount(); i++) {
                        if (i == childCount) {
                            View childView = diaListview.getChildAt(i);
                            RadioButton radioButton = (RadioButton) childView.findViewById(R.id.poi_dia_radioBt);
                            radioButton.setChecked(false);
                        }
                    }

                    childCount = position;
                    alertDialog.dismiss();

                    SharedPreferences.Editor editor_range = getSharedPreferences("editor_range",MODE_PRIVATE).edit();
                    editor_range.putString("range",ranges);
                    editor_range.commit();


                    poiRangeTextView.setText(ranges);
                    range = ranges;
                    getPoi(coordinate, q, range, counts);
                }
            });
            return view;
        }
    }
    //

    //初始化数据
    private void InitData() {
        String s1 = "1000m内";
        rangeDiaList.add(s1);
        String s2 = "2000m内";
        rangeDiaList.add(s2);
        String s3 = "3000m内";
        rangeDiaList.add(s3);
        String s4 = "4000m内";
        rangeDiaList.add(s4);
        String s5 = "5000m内";
        rangeDiaList.add(s5);
    }

    //获取到Poi
    private void getPoi(final String coordinate, final String q, final String range, final int counts) {
        progressDialog = new ProgressDialog(PoiListActivity.this);
        progressDialog.setMessage("正在加载,请稍等...");
        progressDialog.show();
        hashMapList.clear();
        AsyncTask<String, Integer, Integer> asyncTask = new AsyncTask<String, Integer, Integer>() {
            //            String coordinate = "108.884081,34.216924";
            @Override
            protected Integer doInBackground(String... params) {
                String name;
                String address;
                String tel;
                String distance;
                String x;
                String y;
                try {
                    PoiResult poiResult = new PoiResult();
                    poiList = poiResult.ResultPoi(coordinate, q, range, counts);
                    for (int i = 0; i < poiList.size(); i++) {
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        PoiDetails poiDetails = poiList.get(i);
                        address = poiDetails.getAddress();
                        //对获取的地址进行处理
                        if (address.equals("")) {
                            hashMap.put("address", "暂无数据");
                        } else {
                            hashMap.put("address", address);
                        }
                        Distance dis = new Distance();
                        distance = dis.deDistance(poiDetails.getDistance());
                        hashMap.put("distance", distance);
                        name = poiDetails.getName();
                        hashMap.put("name", name);
                        tel = poiDetails.getTel();
                        hashMap.put("tel", tel);
                        x = poiDetails.getX();
                        hashMap.put("x", x);
                        y = poiDetails.getY();
                        hashMap.put("y", y);
                        Log.d("test_address", poiDetails.getAddress());
                        Log.d("test_distance", poiDetails.getDistance());
                        Log.d("test_name", poiDetails.getName());
                        Log.d("test_tel", poiDetails.getTel());
                        Log.d("test_x", poiDetails.getX());
                        Log.d("test_y", poiDetails.getY());
                        hashMapList.add(hashMap);
                    }
                } catch (IOException e) {
                    Log.d("---", "出错了");
                    f = 1;
                } catch (JSONException e) {
                    Log.d("---", "网络出错了");
                    f = 2;
                }
                return f;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                progressDialog.dismiss();
                if (f == 1) {
                    Toast.makeText(PoiListActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                } else if (f == 2) {
                    Toast.makeText(PoiListActivity.this, "服务器繁忙，请稍候再试", Toast.LENGTH_SHORT).show();
                } else if (f == 0) {
                    adapter1 = new PoiListSimapleAdapter(
                            PoiListActivity.this,
                            hashMapList,
                            R.layout.poilist_item,
                            new String[]{"name", "address", "distance"},
                            new int[]{R.id.poiname_TextView, R.id.poiaddress_TextView, R.id.poidistance_TextView}
                    );
                    poi_list_ListView.setAdapter(adapter1);
                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
        };

        asyncTask.execute();
    }

    class PoiListSimapleAdapter extends SimpleAdapter {
        int resourceId;

        public PoiListSimapleAdapter(Context context, List<? extends Map<String, String>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            resourceId = resource;
        }

        @Override
        public int getCount() {
            return hashMapList.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//            if (position == hashMapList.size()) {
//                View view = LayoutInflater.from(PoiListActivity.this).inflate(R.layout.morepoi, null);
//                view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 80));
//                return view;
//            } else {
                HashMap<String, String> map = (HashMap<String, String>) getItem(position);
                String name = map.get("name").toString();
                String address = map.get("address").toString();
                String distance = map.get("distance").toString();
                View view = LayoutInflater.from(PoiListActivity.this).inflate(resourceId, null);
                TextView nameTextView = (TextView) view.findViewById(R.id.poiname_TextView);
                nameTextView.setText(name);
                TextView addressTextView = (TextView) view.findViewById(R.id.poiaddress_TextView);
                addressTextView.setText(address);
                TextView distanceTextView = (TextView) view.findViewById(R.id.poidistance_TextView);
                distanceTextView.setText(distance);
                view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 80));
                return view;
//            }
        }
    }
    //扎点
    private void overlay(double x, double y,String name) {
        LatLng latLng = new LatLng(x, y);
        OverlayOptions overlayOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor).zIndex(9).draggable(false).title(name);
        marker = (Marker) baiduMap.addOverlay(overlayOptions);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                baiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        myLocation.stop();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }
}
